﻿using ConsoleApp;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml.Serialization;

namespace ConsoleApp
{
   public class CloneExtension
    {
        public void Show()
        {
            #region 浅拷贝的效果
            {
                var student = new Student() { id = 1, name = "LJH" };
                var student2 = student;
                student2.name = "Bruke";
            }
            #endregion

            #region 深拷贝的效果
            {
                var student = new Student() { id = 1, name = "LJH" };
                var student2 = JsonConvert.DeserializeObject<Student>(JsonConvert.SerializeObject(student));
                student2.name = "Bruke";

                var student3 = Clone(student);
                var student4 = CloneByJson(student);
                var student5 = CloneByReflect(student);
                var student6 = CloneByXml(student);
            }
            #endregion
        }


        /// <summary>
        /// 克隆(XmlSerializer)
        /// 推荐级：5星
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="inputObj"></param>
        /// <returns></returns>
        public static T CloneByXml<T>(T inputObj)
        {
            if (inputObj == null)
                return default(T);
            using (Stream stream = new MemoryStream())
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(stream, inputObj);
                stream.Seek(0, SeekOrigin.Begin);
                return (T)serializer.Deserialize(stream);
            }
        }

        /// <summary>
        /// 克隆(NewtonsoftJson)
        /// </summary>
        /// <remarks>推荐级：3星</remarks>
        /// <typeparam name="T"></typeparam>
        /// <param name="inputObj"></param>
        /// <returns></returns>
        public static T CloneByJson<T>(T inputObj)
        {
            if (inputObj == null)
                return default(T);
            var deserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };
            return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(inputObj), deserializeSettings);
        }

        /// <summary>
        /// 克隆(Reflect)
        /// </summary>
        /// <remarks>推荐级：3星</remarks>
        /// <typeparam name="T"></typeparam>
        /// <param name="inputObj"></param>
        /// <returns></returns>
        public static T CloneByReflect<T>(T inputObj)
        {
            //如果是字符串或值类型则直接返回
            if (inputObj is string || inputObj.GetType().IsValueType) return inputObj;
            object retval = Activator.CreateInstance(inputObj.GetType());
            FieldInfo[] fields = inputObj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
            foreach (FieldInfo field in fields)
            {
                try { field.SetValue(retval, CloneByReflect(field.GetValue(inputObj))); }
                catch { }
            }
            return (T)retval;
        }

        /// <summary>
        /// 标准克隆([Serializable])
        /// 被克隆类头部需要标识[Serializable]这个特性
        /// </summary>
        /// <remarks>推荐级：4星</remarks>
        /// <typeparam name="T"></typeparam>
        /// <param name="inputObj"></param>
        /// <returns></returns>
        public static T Clone<T>(T inputObj)
        {
            if (!typeof(T).IsSerializable)
            {
                throw new ArgumentException("The type must be serializable.", "source");
            }

            if (Object.ReferenceEquals(inputObj, null))
            {
                return default(T);
            }

            System.Runtime.Serialization.IFormatter formatter = new BinaryFormatter();
            Stream stream = new MemoryStream();
            using (stream)
            {
                formatter.Serialize(stream, inputObj);
                stream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(stream);
            }
        }


    }
}
